<template>
    <div>
      <!-- 面包屑 -->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>分类参数</el-breadcrumb-item>
      </el-breadcrumb>
      <!-- 卡片试图 -->
      <el-card class="box-card">
        <!-- 提示区域 -->
        <el-alert
          title="注意：只允许为第三级分类设置相关参数！"
          :closable="false"
          type="warning"
          show-icon>
        </el-alert>
        <!-- 选择商品分类 -->
        <div class="selectCate">
          选择商品分类：
          <el-cascader
            v-model="selectCateValue"
            :options="cateList"
            :props="cascaderProps"
            @change="cascaderChange">
          </el-cascader>
        </div>
        <!-- 标签页 -->
        <el-tabs v-model="activeName" @tab-click="tabsClick">
          <!-- 动态参数 -->
          <el-tab-pane label="动态参数" name="many">
            <el-button @click="addParamsDialogVisible=true" type="primary" size="mini" :disabled="isBtnDisable">添加参数</el-button>
            <!-- 动态参数表格 -->
            <el-table :data="manyTable" border stripe>
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <el-tag @close="closeTag(scope.row,index)" closable v-for="(item,index) in scope.row.attr_vals" :key="index">{{ item }}</el-tag>
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                  >
                  </el-input>
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                </template>
              </el-table-column>
              <el-table-column type="index" label="#"></el-table-column>
              <el-table-column label="参数名称" prop="attr_name"></el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button @click="showEditDialog(scope.row.attr_id)" size="mini" type="primary" icon="el-icon-edit">修改</el-button>
                  <el-button @click="removeAttr(scope.row.attr_id)" size="mini" type="danger" icon="el-icon-delete">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <!-- 静态属性 -->
          <el-tab-pane label="静态属性" name="only">
            <el-button @click="addParamsDialogVisible='true'" type="primary" size="mini" :disabled="isBtnDisable">添加属性</el-button>
            <!-- 静态属性表格 -->
            <el-table :data="onlyTable" border stripe>
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <el-tag @close="closeTag(scope.row,index)" closable v-for="(item,index) in scope.row.attr_vals" :key="index">{{ item }}</el-tag>
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                  >
                  </el-input>
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                </template>
              </el-table-column>
              <el-table-column type="index" label="#"></el-table-column>
              <el-table-column label="参数名称" prop="attr_name"></el-table-column>
              <el-table-column label="操作">
                <template>
                  <el-button size="mini" type="primary" icon="el-icon-edit">修改</el-button>
                  <el-button size="mini" type="danger" icon="el-icon-delete">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <!-- 添加动态参数/静态属性对话框 -->
      <el-dialog
        @close="closeAddParams()"
        :title="'添加'+titleText"
        :visible.sync="addParamsDialogVisible"
        width="50%">
        <el-form :model="addParamsForm" :rules="addParamsRules" ref="addParamsRef" label-width="100px" class="demo-ruleForm">
          <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="addParamsForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addParamsDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addParams()">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改动态参数/静态属性对话框 -->
      <el-dialog
        @close="closeEditParams()"
        :title="'编辑'+titleText"
        :visible.sync="editParamsDialogVisible"
        width="50%">
        <el-form :model="editParamsForm" :rules="editParamsRules" ref="editParamsRef" label-width="100px" class="demo-ruleForm">
          <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="editParamsForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editParamsDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editParams()">确 定</el-button>
        </span>
      </el-dialog>
    </div>
</template>

<script>
export default {
  data() {
    return {
      // 商品分类数据
      cateList: [],
      // 级联选择器双向绑定的数据
      selectCateValue: [],
      cascaderProps: { 
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id'
      },
      activeName: 'many',
      // 动态参数列表
      manyTable: [],
      // 静态属性列表
      onlyTable: [],
      // 控制添加动态参数/静态属性
      addParamsDialogVisible: false,
      // 添加参数的表单
      addParamsForm: {
        attr_name: ''
      },
      // 添加参数表单的校验规则
      addParamsRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
          { min: 2, max:7, message: '长度在 2 到 7 个字符', trigger: 'blur' }
        ]
      },
      // 编辑表单
      // 控制编辑对话框
      editParamsDialogVisible: false,
      // 编辑表单的数据对象
      editParamsForm: {},
      // 编辑表单的校验规则
      editParamsRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
          { min: 2, max:7, message: '长度在 2 到 7 个字符', trigger: 'blur' }
        ]
      },
      // 控制添加参数输入框显示隐藏
      inputVisible: false,
      inputValue: ''
    }
  },

  created() {
    this.getCateList()
  },

  computed: {
    // 控制按钮是否禁用
    isBtnDisable () {
      return this.selectCateValue.length!==3
    },
    // 三级分类Id
    catdId () {
      if(this.selectCateValue.length === 3) return this.selectCateValue[2]
      return null
    },
    // 计算标题文字
    titleText () {
      return this.activeName === 'many'? '动态参数':'静态属性'
    }
  },

  methods: {
    // 获取商品分类数据
    async getCateList () {
      const {data: res} = await this.$axios.get('categories')
      if(res.meta.status !== 200) return this.$message.error('获取失败')
      this.cateList = res.data
    },
    // 获取参数
    async getParams () {
      if(this.selectCateValue.length !== 3){
        this.selectCateValue = []
        this.manyTable = []
        this.onlyTable = []
        return 
      } 
      // 发送请求或者参数列表
      // 分类id：this.selectCateValue[2]
      // 
      const {data: res} = await this.$axios.get(`categories/${this.catdId}/attributes`,{
        params: {
          sel: this.activeName
        }
      })
      res.data.forEach(item=>{
        item.attr_vals = item.attr_vals === ''?[]:item.attr_vals.split(' ')
        item.inputVisible = false 
        item.inputValue =''
      })
      if(this.activeName === 'many') return this.manyTable = res.data 
      this.onlyTable = res.data
    },
    // 级联选择变化
    cascaderChange () {
      this.getParams()
    },
    // 点击了tabs标签页触发
    tabsClick () {
      this.getParams()
    },
    // 关闭添加参数对话框
    closeAddParams () {
      this.$refs.addParamsRef.resetFields()
    },
    // 关闭编辑参数对话框
    closeEditParams () {
      this.$refs.editParamsRef.resetFields()
    },
    // 添加参数
    addParams () {
      // 先校验表单是否合法
      this.$refs.addParamsRef.validate(async flag=>{
        if(!flag) return 
        // 1. 分类id-url:id：this.catdId
        // 2. 参数名称-attr_name: this.addParamsForm.attr_name
        // 3. 参数类型-sel：this.activeName
        const { data: res } = await this.$axios.post(`categories/${this.catdId}/attributes`,{
          attr_name: this.addParamsForm.attr_name,
          attr_sel: this.activeName
        })
        if(res.meta.status !== 201) return this.$message.error('创建失败')
        this.$message.success('创建成功')
        this.addParamsDialogVisible = false 
        this.getParams()
      })
    },
    // 点击修改
    async showEditDialog (attr_id) {
      const {data: res} = await this.$axios.get(`categories/${this.catdId}/attributes/${attr_id}`,{
        params: {attr_sel: this.activeName}
      })
      if(res.meta.status !== 200) return this.$message.error('亲，获取数据失败了呦')
      this.editParamsForm = res.data
      this.editParamsDialogVisible = true
    },
    // 完成编辑操作
    editParams () {
      this.$refs.editParamsRef.validate(async flag=>{
        if(!flag) return 
        const {data: res} = await this.$axios.put(`categories/${this.catdId}/attributes/${this.editParamsForm.attr_id}`,{
          attr_name: this.editParamsForm.attr_name,
          attr_sel: this.activeName
        })
        if(res.meta.status !== 200) return this.$message.error('更新失败')
        this.$message.success('更新成功')
        this.editParamsDialogVisible = false 
        this.getParams()
      })
    },
    // 完成删除参数/属性
    removeAttr (attrId) {
      this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$axios.delete(`categories/${this.catdId}/attributes/${attrId}`)
        if(res.meta.status !== 200) return this.$message.error('删除失败')
        this.$message.success('删除成功')
        this.getParams()
      }).catch(() => {
        this.$message('已取消删除')
      })
    },
    // 鼠标失去焦点或者敲回车
    handleInputConfirm (row) {
      console.log(123)
      if(row.inputValue.trim() === '') {
        row.inputValue = ''
        row.inputVisible = false
        return 
      }
      console.log('合法内容',row)
      // 1.分类 ID：this.catdId
      // 2.属性 ID: row.attr_id
      // 3.attr_name: row.attr_name
      // 4.attr_sel：this.activeName
      // 5.attr_vals: 中,美,日,中1,中国,中国加油,武汉加油,中国加油23 输入框的值：123
      // 中,美,日,中1,中国,中国加油,武汉加油,中国加油23 中版 123 456 789
      row.attr_vals.push(row.inputValue)
      this.saveAttrVals(row)
      row.inputValue = ''
      row.inputVisible = false
    },
    // 封装删除和添加
    async saveAttrVals (row) {
      const { data: res } = await this.$axios.put(`categories/${this.catdId}/attributes/${row.attr_id}`,{
        attr_name: row.attr_name,
        attr_sel: this.activeName,
        attr_vals: row.attr_vals.join(' ')
      })
      if(res.meta.status !== 200) return this.$message.error('更新失败')
      this.$message.success('更新成功')
    },
    // 点击NEW Tag
    showInput (row) {
      row.inputVisible = !row.inputVisible
      // 当前组件重新渲染完成了
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    // 删除参数项
    async closeTag (row,index) {
      row.attr_vals.splice(index,1)
      this.saveAttrVals(row)
    }
  }
};
</script>

<style scoped lang='less'>
.selectCate {
  margin: 20px 0;
}

.el-tag{
  margin: 7px;
}
.input-new-tag {
  width: 120px;
}
</style>
